<?php
namespace app\api\controller;
use app\common\controller\ApiBase;
use think\facade\Request;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Session;
use app\api\model\User as Yonghu;

class User extends ApiBase
{
    protected $noAuth = ['index','edit_user', 'update_userinfo','get_code','logout'];
    
    protected function _initialize()
    {
        parent::_initialize();
        
    }
    //个人中心
    public function index()
    {
        $info = Session::get('user_auth');
        //用户基本信息
        $userinfo = Yonghu::with(['shop'])->where(['id'=> UserId()])->find();
        $this->result(['userinfo' => $userinfo,'islogin' => '1'], '0', '获取成功', 'json');
    }
    //编辑个人资料
    public function edit_user()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();            
            $result = Yonghu::where(['id'=> UserId()])->strict(false)->save($param);
            insert_api_log('修改了个人资料');
            $this->result($result, '0', '修改成功', 'json');
        }else{
            $data = Yonghu::where(['id'=> UserId()])->find();
            $this->result(['user'=>$data,'message'=>Newmessage()], '0', '获取成功', 'json');
        }
    }
    //一键更新用户信息
    public function update_userinfo()
    {
        $data['avatarurl'] = input('avatarurl');
        $data['name'] = input('name');
        Yonghu::where(['id'=> Wechat_userid()])->update($data);
        $this->result($data, '0', '获取成功', 'json');
    }
    //获取验证码
    public function get_code($mobile)
    {
        //检查手机号码格式
        try{
            $this->validate(['mobile'=>$mobile], 'mobile');
        }catch (\Exception $e){
            $this->result('', '-3',$e->getMessage(), 'json');
        }
        //检查当天验证次数
        $code = UserCode::where(['shop_id'=> ShopId()])->whereDay('create_time')->order('id desc')->count();
        if($code > '5'){
            $this->result('', '-3', '验证次数超额,请明天再试!', 'json');
        }
        //创建验证码
        $code = rand_number(6);
        UserCode::create(['shop_id'=> ShopId(),'mobile'=>$mobile,'code'=>$code,'exp_time'=>time()+600]);
        \app\common\model\Sms::sendCode($mobile,$code);
        $this->result('', '0', '发送成功', 'json');
    }
    //退出登录
    public function logout()
    {
        Session::delete('api_auth');
        Session::delete('api_auth_sign');
        $this->result('', '0', '退出成功', 'json');
    }
    
 
    
    
}
